package csc.daonjpa.java.dao;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.domain.Log;

@Repository
public class LogDAO {
	
	@PersistenceContext
	EntityManager entityManager;
	
	/**
	 * @return the entityManager
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * @param entityManager the entityManager to set
	 */
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Transactional
	public void createLog(String content, Long customerId) {
		Date today = new Date();
		DateFormat format = new SimpleDateFormat("yy-MM-dddd hh:mm:ss");
		//get logdate String
		String todayString = format.format(today);
		Log log = new Log();
		try{
			Customer customer = entityManager.find(Customer.class, customerId);
			log.setContent(content);
			log.setDateTime(todayString);
			log.setCusLog(customer);
			entityManager.persist(log);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@Transactional
	public void createLog(String content, Customer customer) {
		try{
			Date today = new Date();
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			//get logdate String
			String todayString = format.format(today);
			Log log = new Log();
			log.setContent(content);
			log.setDateTime(todayString);
			log.setCusLog(customer);
			entityManager.persist(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public List<Log> getLogs(){
		List<Log> logs = null;
		try{
			TypedQuery<Log> query = entityManager.createQuery("SELECT l FROM Log l", Log.class);
			logs = query.getResultList();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return logs;
	}
	
}
